<!-- 组件 -->
<template>
  <view>
    <van-cell-group>
      <van-field
        v-show="!props.hidden"
        clickable
        clearable
        v-model="_value"
        type="number"
        :readonly="props.readonly"
        :required="props.required"
        :name="props.formItem?.id"
        :label="props.formItem?.title"
        :placeholder="props.placeholder"
        :rules="rules"
        :input-align="FieldInputAlign.DEFAULT"
      />
    </van-cell-group>
  </view>
</template>

<script setup lang="ts">
  import { computed, watch } from 'vue';
  import { isEmpty } from '@/utils/is';
  import { evalFormual } from '@/utils/evalFormual';
  import { FieldInputAlign } from '@/enums/formEnum';
  const emits = defineEmits(['update:value', 'labelShow']);
  const props = defineProps({
    value: {
      type: String,
      default: '',
    },
    required: {
      type: Boolean,
      default: false,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    //隐藏组件的公共属性
    formula: {
      type: Object,
      default: () => {
        return {
          showFormula: '', //回显用，因为包含表单字段的时候会出现表单名称
          calcFormula: '', //解析用，表单名称对应为formData.fieldxxxx
        };
      },
    },
    formItem: {
      type: Object,
      default: () => {},
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    rule: {
      type: Object,
      default: () => null,
    },
    placeholder: {
      type: String,
      default: '请输入数值',
    },
    precision: {
      type: Number,
      default: 0,
    },
    hidden: {
      type: Boolean,
      default: false,
    },
  });
  /** 计算属性：_value */
  const _value = computed({
    get() {
      return isEmpty(props.value) ? null : parseNumber(props.value);
    },
    set(val) {
      emits('update:value', isEmpty(val) ? null : parseNumber(val));
    },
  });
  const parseNumber = (val: string) => {
    return props.precision > 0
      ? parseFloat(parseFloat(val).toFixed(props.precision))
      : parseInt(val);
  };
  /** 校验规则 */
  const rules = computed(() => {
    if (isEmpty(props.rule)) {
      return [];
    } else {
      return props.rule;
    }
  });

  const doFormula = () => {
    let hidden = evalFormual(props.formula.calcFormula, props.formData);
    //如果隐藏，同时也隐藏label,通知父组件去隐藏，因为label不在当前界面
    //调用父组件FormDesignRender 的方法：
    emits('labelShow', props.formItem, hidden);
  };

  watch(
    () => props.formData,
    () => {
      doFormula();
    },
    { immediate: true, deep: true },
  );
</script>

<style scoped></style>
